package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.Address;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.edu.tju.elm.service.AddressService;
import cn.edu.tju.core.utils.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @PostMapping
    public HttpResult create(@RequestBody Address address) {
        boolean saved = addressService.save(address);
        return saved ? HttpResult.ok(address) : HttpResult.fail("创建失败");
    }

    @GetMapping("/user/{userId}")
    public HttpResult listByUser(@PathVariable Long userId) {
        QueryWrapper<Address> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        return HttpResult.ok(addressService.list(qw));
    }

    @GetMapping("/{id}")
    public HttpResult getById(@PathVariable Long id) {
        Address address = addressService.getById(id);
        return address != null ? HttpResult.ok(address) : HttpResult.fail("地址不存在");
    }

    @PutMapping("/{id}")
    public HttpResult update(@PathVariable Long id, @RequestBody Address address) {
        address.setId(id);
        boolean updated = addressService.updateById(address);
        return updated ? HttpResult.ok(address) : HttpResult.fail("更新失败");
    }

    @DeleteMapping("/{id}")
    public HttpResult delete(@PathVariable Long id) {
        boolean removed = addressService.removeById(id);
        return removed ? HttpResult.ok(true) : HttpResult.fail("删除失败");
    }
}



